<?php
/**
 * 接口请求日志
 * User: cxm
 * Date: 2020/12/23
 * Time: 15:13
 */
namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ApiLog
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle(Request $request, \Closure $next)
    {
        $user = Auth::guard('api')->user();
        $log_array = [
            'uuid'    => guid(),
            'user_id' => isset($user) ? Auth::guard('api')->user()->id : 0,
            'path'    => $request->path(),
            'method'  => $request->method(),
            'ip'      => $request->getClientIp(),
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Unknown', // 服务器头信息
            'input'   => json_encode($request->input()),
            'header'    => json_encode($request->header()),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        \App\Models\ApiLog::insert($log_array);

        return $next($request);
    }
}